package com.cam.test.wechat.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cam.framework.utils.CacheUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WechatUtils {

    private static String appId;

    private static String appSecret;

    private static String videoLiveId;

    private static String videoLiveSecret;

    private static String videoId;

    private static RestTemplate restTemplate;

    public WechatUtils(@Value("${wechat.miniprogram.appid}") String appId, @Value("${wechat.miniprogram.appsecret}") String appSecret,
                       @Value("${wechat.videoChannel.videoId}")String videoId, @Value("${wechat.videoChannel.liveid}")String videoLiveId, @Value("${wechat.videoChannel.livesecret}")String videoLiveSecret) {
        WechatUtils.appId = appId;
        WechatUtils.appSecret = appSecret;
        WechatUtils.videoId = videoId;
        WechatUtils.videoLiveId = videoLiveId;
        WechatUtils.videoLiveSecret = videoLiveSecret;
        WechatUtils.restTemplate = new RestTemplate();
    }

    public static List<HashMap> getVideoNoticeList() {
        System.out.println("获取视频号直播预约列表请求");
        String accessToken = getVideoAccessToken();
        String requestUri = "https://api.weixin.qq.com/channels/ec/finderlive/getfinderlivenoticerecordlist?access_token=" + accessToken;
        Map<String, String> requestParams = new HashMap<>();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(requestUri, requestParams, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()){
            System.out.println(responseEntity.getBody());
            JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
            if (jsonObject.containsKey("errcode") && jsonObject.getInt("errcode") == 0) {
                System.out.println("获取视频号直播列表成功");
                JSONArray liveList = jsonObject.getJSONArray("live_notice_list");
                List<HashMap> liveMapList = JSONUtil.toList(liveList, HashMap.class);
                return liveMapList;
            } else {
                System.out.println("获取AccessToken失败，errcode：" + jsonObject.getInt("errcode"));
                System.out.println("获取AccessToken失败，errmsg" + jsonObject.getStr("errmsg"));
                throw new RuntimeException("服务器错误，请联系管理员");
            }
        } else {
            System.out.println("获取视频号直播列表失败，响应状态码：" + responseEntity.getStatusCode());
            System.out.println("获取视频号直播列表失败，响应体" + responseEntity.getBody());
            throw new RuntimeException("服务器错误，请联系管理员");
        }
    }

    public static List<HashMap> getVideoLive() {
        System.out.println("获取视频号直播列表请求");
        String accessToken = getVideoAccessToken();
        String requestUri = "https://api.weixin.qq.com/channels/ec/finderlive/getfinderliverecordlist?access_token=" + accessToken;
        Map<String, String> requestParams = new HashMap<>();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(requestUri, requestParams, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()){
            System.out.println(responseEntity.getBody());
            JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
            if (jsonObject.containsKey("errcode") && jsonObject.getInt("errcode") == 0) {
                System.out.println("获取视频号直播列表成功");
                JSONArray liveList = jsonObject.getJSONArray("live_list");
                List<HashMap> liveMapList = JSONUtil.toList(liveList, HashMap.class);
                return liveMapList;
            } else {
                System.out.println("获取AccessToken失败，errcode：" + jsonObject.getInt("errcode"));
                System.out.println("获取AccessToken失败，errmsg" + jsonObject.getStr("errmsg"));
                throw new RuntimeException("服务器错误，请联系管理员");
            }
        } else {
            System.out.println("获取视频号直播列表失败，响应状态码：" + responseEntity.getStatusCode());
            System.out.println("获取视频号直播列表失败，响应体" + responseEntity.getBody());
            throw new RuntimeException("服务器错误，请联系管理员");
        }
    }

    public static String getAccessToken() {
//        String accessToken = (String) RedisUtils.getInstance().get(CacheNames.XCX_CACHE_ACCESS_TOKEN);
        String accessToken = (String) CacheUtils.getCache("wechat_access_token");
        if (StringUtils.isEmpty(accessToken)) {
            System.out.println("未发现AccessToken缓存，重新请求");
            String requestUri = "https://api.weixin.qq.com/cgi-bin/token?appid={appid}&secret={secret}&grant_type={grantType}";
            Map<String, String> requestParams = new HashMap<String, String>() {{
                put("appid", appId);
                put("secret", appSecret);
                put("grantType", "client_credential");
            }};
//        String responseString = restTemplate.getForObject(requestUri, String.class, requestParams);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUri, String.class, requestParams);
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
                accessToken = jsonObject.getStr("access_token");
                CacheUtils.setCache("wechat_access_token", accessToken);
                System.out.println("获取AccessToken成功，缓存已刷新");
//                RedisUtils.getInstance().set(CacheNames.XCX_CACHE_ACCESS_TOKEN, accessToken);
//                RedisUtils.getInstance().expire(CacheNames.XCX_CACHE_ACCESS_TOKEN, 6000);
            } else {
                System.out.println("获取AccessToken失败，响应状态码：" + responseEntity.getStatusCode());
                System.out.println("获取AccessToken失败，响应体" + responseEntity.getBody());
                throw new RuntimeException("服务器错误，请联系管理员");
            }
        }
        return accessToken;
    }

    public static String getVideoAccessToken() {
//        String accessToken = (String) RedisUtils.getInstance().get(CacheNames.XCX_CACHE_ACCESS_TOKEN);
        String accessToken = (String) CacheUtils.getCache("wechat_video_access_token");
        if (StringUtils.isEmpty(accessToken)) {
            System.out.println("未发现VideoAccessToken缓存，重新请求");
            String requestUri = "https://api.weixin.qq.com/cgi-bin/token?appid={appid}&secret={secret}&grant_type={grantType}";
            Map<String, String> requestParams = new HashMap<String, String>() {{
                put("appid", videoLiveId);
                put("secret", videoLiveSecret);
                put("grantType", "client_credential");
            }};
//        String responseString = restTemplate.getForObject(requestUri, String.class, requestParams);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUri, String.class, requestParams);
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
                accessToken = jsonObject.getStr("access_token");
                CacheUtils.setCache("wechat_video_access_token", accessToken);
                System.out.println("获取VideoAccessToken成功，缓存已刷新");
//                RedisUtils.getInstance().set(CacheNames.XCX_CACHE_ACCESS_TOKEN, accessToken);
//                RedisUtils.getInstance().expire(CacheNames.XCX_CACHE_ACCESS_TOKEN, 6000);
            } else {
                System.out.println("获取VideoAccessToken失败，响应状态码：" + responseEntity.getStatusCode());
                System.out.println("获取VideoAccessToken失败，响应体" + responseEntity.getBody());
                throw new RuntimeException("服务器错误，请联系管理员");
            }
        }
        return accessToken;
    }
}
